<template>
  <div class="order-list">
    <div class="page-header">
      <h1>我的订单</h1>
      <p>查看和管理您的所有预约订单</p>
    </div>

    <el-button
      v-if="isPhotographer"
      type="primary"
      @click="goToPhotographerOrders"
      style="margin-bottom: 20px"
    >
      管理用户下单关联我的订单
    </el-button>

    <!-- 订单筛选 -->
    <el-card class="filter-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-select v-model="filters.status" placeholder="订单状态" clearable>
            <el-option label="待支付" value="PENDING" />
            <el-option label="已确认" value="CONFIRMED" />
            <el-option label="拍摄中" value="IN_PROGRESS" />
            <el-option label="已完成" value="COMPLETED" />
            <el-option label="已取消" value="CANCELED" />
          </el-select>
        </el-col>
        <el-col :span="10">
          <el-date-picker
            v-model="filters.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%;"
          />
        </el-col>
        <el-col :span="8" style="display: flex; align-items: center;">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetFilters" style="margin-left: 10px;">重置</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 订单列表 -->
    <div class="orders-container">
      <el-card v-for="order in filteredOrders" :key="order.id" class="order-card">
        <div class="order-header">
          <div class="order-info">
            <h3>订单号：{{ order.id }}</h3>
            <el-tag :type="getStatusType(order.status)">
              {{ getStatusText(order.status) }}
            </el-tag>
          </div>
          <div class="order-actions">
            <el-button size="small" @click="viewOrderDetail(order.id)">查看详情</el-button>
            <el-button 
              v-if="order.status === 'PENDING'" 
              type="primary" 
              size="small" 
              @click="handlePay(order)"
            >
              立即支付
            </el-button>
            <el-button 
              v-if="order.status === 'CONFIRMED'" 
              type="success" 
              size="small" 
              @click="startChat(order.id)"
            >
              联系摄影师
            </el-button>
            <el-button 
              v-if="order.status === 'PENDING'" 
              type="danger" 
              size="small" 
              @click="cancelOrder(order.id)"
            >
              取消订单
            </el-button>
          </div>
        </div>

        <div class="order-content">
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="photographer-info">
                <img :src="order.photographer?.avatar" class="photographer-avatar" />
                <div>
                  <h4>{{ order.photographer?.name }}</h4>
                  <p>{{ order.photographer?.style }}</p>
                </div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="order-details">
                <p><strong>拍摄套餐：</strong>{{ order.packageName }}</p>
                <p><strong>拍摄时间：</strong>{{ formatDateTime(order.shootingTime) }}</p>
                <p><strong>拍摄地点：</strong>{{ order.shootingLocation }}</p>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="order-price">
                <p class="price">¥{{ order.totalPrice }}</p>
                <p class="create-time">创建时间：{{ formatDateTime(order.createTime) }}</p>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-card>
    </div>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 支付对话框 -->
    <el-dialog v-model="payDialogVisible" title="订单支付" width="400px">
      <div class="pay-info">
        <p><strong>订单号：</strong>{{ selectedOrder?.id }}</p>
        <p><strong>支付金额：</strong>¥{{ selectedOrder?.totalPrice }}</p>
        <p><strong>拍摄套餐：</strong>{{ selectedOrder?.packageName }}</p>
      </div>
      <template #footer>
        <el-button @click="payDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmPay" :loading="payLoading">
          确认支付
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '../utils/api'
import dayjs from 'dayjs'

const router = useRouter()
const userStore = useUserStore()
const isPhotographer = ref(false)

enum OrderStatus {
  PENDING = 'PENDING',
  CONFIRMED = 'CONFIRMED',
  IN_PROGRESS = 'IN_PROGRESS',
  COMPLETED = 'COMPLETED',
  CANCELED = 'CANCELED',
  FAILED = 'FAILED'
}

interface Photographer {
  id: number
  name: string
  style: string
  avatar: string
}

interface Order {
  id: number
  userId: number
  photographerId: number
  packageName: string
  totalPrice: number
  shootingTime: string
  shootingLocation: string
  status: OrderStatus
  createTime: string
  updateTime: string
  photographer?: Photographer
}

// 数据
const orders = ref<Order[]>([])
const filteredOrders = ref<Order[]>([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)

// 筛选条件
const filters = reactive({
  status: '',
  dateRange: []
})

// 支付相关
const payDialogVisible = ref(false)
const payLoading = ref(false)
const selectedOrder = ref<Order | null>(null)

// 获取订单列表
const fetchOrders = async () => {
  try {
    loading.value = true
    const res = await api.get(`/orders/user/${userStore.user?.id}`)
    orders.value = res.data || []
    filteredOrders.value = orders.value // 初始化显示全部
    total.value = orders.value.length
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  let filtered = orders.value
  if (filters.status) {
    filtered = filtered.filter(order => order.status === filters.status)
  }
  if (filters.dateRange && filters.dateRange.length === 2) {
    const [start, end] = filters.dateRange
    filtered = filtered.filter(order => {
      return (
        dayjs(order.createTime).isAfter(dayjs(start).subtract(1, 'day')) &&
        dayjs(order.createTime).isBefore(dayjs(end).add(1, 'day'))
      )
    })
  }
  filteredOrders.value = filtered
}

// 重置筛选
const resetFilters = () => {
  Object.assign(filters, {
    status: '',
    dateRange: []
  })
  filteredOrders.value = orders.value
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchOrders()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchOrders()
}

// 获取状态类型
const getStatusType = (status: OrderStatus) => {
  const statusMap: Record<OrderStatus, string> = {
    PENDING: 'warning',
    CONFIRMED: 'primary',
    IN_PROGRESS: 'success',
    COMPLETED: 'success',
    CANCELED: 'info',
    FAILED: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: OrderStatus) => {
  const statusMap: Record<OrderStatus, string> = {
    PENDING: '待支付',
    CONFIRMED: '已确认',
    IN_PROGRESS: '拍摄中',
    COMPLETED: '已完成',
    CANCELED: '已取消',
    FAILED: '已失败'
  }
  return statusMap[status] || '未知状态'
}

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  return dayjs(dateTime).format('YYYY-MM-DD HH:mm')
}

// 查看订单详情
const viewOrderDetail = (orderId: number) => {
  router.push(`/order/${orderId}`)
}

// 支付处理
const handlePay = (order: Order) => {
  selectedOrder.value = order
  payDialogVisible.value = true
}

// 确认支付
const confirmPay = async () => {
  try {
    payLoading.value = true
    // 这里应该调用支付API
    // await api.post(`/api/orders/${selectedOrder.value.id}/pay`)
    
    ElMessage.success('支付成功！')
    payDialogVisible.value = false
    fetchOrders() // 刷新订单列表
  } catch (error) {
    console.error('支付失败:', error)
    ElMessage.error('支付失败，请重试')
  } finally {
    payLoading.value = false
  }
}

// 取消订单
const cancelOrder = async (orderId: number) => {
  try {
    await ElMessageBox.confirm('确定要取消这个订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await api.put(`/orders/${orderId}/cancel`, null, {
      params: { userId: userStore.user?.id }
    })
    ElMessage.success('订单已取消')
    fetchOrders()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error)
      ElMessage.error('取消订单失败，请重试')
    }
  }
}

// 开始聊天
const startChat = (orderId: number) => {
  router.push(`/chat/${orderId}`)
}

const createOrder = async (orderData: Partial<Order>) => {
  try {
    const res = await api.post('/orders/user/create', orderData)
    ElMessage.success('预约成功！')
    fetchOrders()
    // 跳转或关闭弹窗等
  } catch (error) {
    ElMessage.error('预约失败，请重试')
  }
}

const checkPhotographer = async () => {
  if (!userStore.user || !userStore.user.id) return
  const res = await api.get('/photo/photographer/list')
  console.log('user id:', userStore.user.id)
  console.log('photographer list:', res.data)
  const photographer = (res.data || []).find(
    (p: any) => userStore.user && p.userId === userStore.user.id
  )
  console.log('isPhotographer:', !!photographer)
  isPhotographer.value = !!photographer
}

const goToPhotographerOrders = () => {
  console.log('go to photographer orders')
  router.push('/photographer/orders')
}

onMounted(() => {
  checkPhotographer()
  fetchOrders()
})
</script>

<style scoped>
.order-list {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.page-header h1 {
  font-size: 2.5rem;
  color: #333;
  margin-bottom: 10px;
}

.page-header p {
  color: #666;
  font-size: 1.1rem;
}

.filter-card {
  margin-bottom: 30px;
}

.orders-container {
  margin-bottom: 40px;
}

.order-card {
  margin-bottom: 20px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.order-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.order-info h3 {
  margin: 0;
  color: #333;
}

.order-actions {
  display: flex;
  gap: 10px;
}

.order-content {
  padding: 10px 0;
}

.photographer-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.photographer-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  object-fit: cover;
}

.photographer-info h4 {
  margin: 0 0 5px 0;
  color: #333;
}

.photographer-info p {
  margin: 0;
  color: #666;
  font-size: 0.9rem;
}

.order-details p {
  margin-bottom: 8px;
  color: #666;
}

.order-details strong {
  color: #333;
}

.order-price {
  text-align: right;
}

.price {
  font-size: 1.5rem;
  font-weight: bold;
  color: #e74c3c;
  margin-bottom: 10px;
}

.create-time {
  color: #999;
  font-size: 0.9rem;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 40px;
}

.pay-info p {
  margin-bottom: 10px;
  color: #666;
}

.pay-info strong {
  color: #333;
}
</style> 